<?php
/**
 * Created by PhpStorm.
 * User: denh
 * Date: 16/7/6
 * Time: 下午7:07
 */

require_once ROOT_PATH . 'bs/BsUserCenter.php';

class WxLoginController extends BaseController {
    function __construct($m = DEFAULT_CONTROLLER, $a = DEFAULT_METHOD) {
        parent::__construct($m, $a);

    }

    #构建获取code值url
    static function wxGzhUrl($m, $a, $parm) {
        $doGzh = new DoPublic_serv_accounts();
        $doGzh->set_id(G_SERV_ID);
        $doGzh->where($doGzh->data)->row();

        $parm = json_encode($parm);

        $url = Tools::url('wxLogin', 'wxGzhLogin', array('parm' => $parm));
        $url = urlencode($url);
        $appId = $doGzh->get_app_id();
        $state = sprintf("%s_%s", $m, $a);
        $pg = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appId}&redirect_uri={$url}&response_type=code&scope=snsapi_base&state={$state}#wechat_redirect";
        return $pg;
    }

    #获取微信用户openid
    function wxGzhLogin() {
        $code = $this->request('code', true);
        $state = $this->request('state', true); #页面
        $parm = $this->request('parm');
        $parm = json_decode($parm, true);

        list($m, $a) = explode('_', $state, 2);
        $doGzh = new DoPublic_serv_accounts();
        $doGzh->set_id(G_SERV_ID);
        $doGzh->where($doGzh->data)->row();

        $appId = $doGzh->get_app_id();
        $secret = $doGzh->get_AppSecret();
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appId}&secret={$secret}&code={$code}&grant_type=authorization_code";
        $re = self::$tools->curl_get_contents($url);
        $obj = json_decode($re);
        if ($obj) {
            logger()->getInstance()->logInfo('自动获取openid结果：' . var_export($obj, true));
            $openId = $obj->openid;
            $_SESSION['vo用户数据']['openID'] = $openId;
            C用户::fg给session赋值();

            $bsUserCenter = new BsUserCenter();
            $bsUserCenter->getInfoFromUserCenter($openId);
            logger()->getInstance()->logInfo('session openID：' . $_SESSION['vo用户数据']['openID']);
            $this->redirect($m, $a, $parm);
        } else {
            Logger::getInstance()->logInfo("[UserController|wxGzhLogin]OpenId get failed!");
        }
    }

}